package com.function.base;

import com.response.ResponseData;
import com.exception.ModbusException;
import com.main.tcp.protocol.RequestFrame;

import java.util.List;

/**
 * 功能吗基础类
 * @author zhujh
 */
public abstract class BaseFunctionAction {

    protected final int RESPONSE_HEADER_LENGTH = 9;

    protected int LENGTH;

    protected Integer functionCode;

    protected Integer expected;

    public BaseFunctionAction() {}


    protected void validDateStartAddress(int startAddress) {
        if (startAddress > 65535 || startAddress < 0) {
            throw new IllegalArgumentException("超出开始地址范围：0~65535");
        }
    }


    public void validateResponseByExpected(byte[] data, Integer expected) throws ModbusException {
        byte expectedByte = (byte)((int)expected);
        if ((data[7] & 0xff) == expectedByte && data[8] == 0x01) {
            throw new ModbusException("========函数不支持========");
        }

        if ((data[7] & 0xff) == expectedByte && data[8] == 0x02) {
            throw new ModbusException("========无效的开始地址========");
        }

        if ((data[7] & 0xff) == expectedByte && data[8] == 0x03) {
            throw new ModbusException("========无效的开始地址数量========");
        }

        if ((data[7] & 0xff) == expectedByte && data[8] == 0x04) {
            throw new ModbusException("========读取失败========");
        }
    }

    protected RequestFrame getRequestFrameByFunction() {
        RequestFrame requestFrame = new RequestFrame(functionCode, LENGTH);
        return requestFrame;
    }

    public abstract void validateSendDataParams();

    public abstract byte[] getReQuestByte();

    public abstract void validateResponse(byte[] response) throws ModbusException;

    public abstract List<ResponseData> getResPonseData(byte[] response);

    public int getLENGTH() {
        return LENGTH;
    }

    public void setLENGTH(int LENGTH) {
        this.LENGTH = LENGTH;
    }
}
